package email;

import java.security.Security;
import java.util.List;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class Sender {
	
	@SuppressWarnings("finally")
	public static synchronized Email sendMail(String remetente,List<String> destinos,String assunto,String mensagem,String protocolo,String host,String auth,String porta,String tls,Email email) {
		Connect conexao = new Connect();
		try {
			// carga del archivo smtp.properties
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

			// Propiedades de la conexion
			Properties props = new Properties();
			props.setProperty("mail.transport.protocol", protocolo);
			props.setProperty("mail.host", host);
			props.put("mail.smtp.auth", auth);
			props.put("mail.smtp.port", porta);
			props.put("mail.smtp.socketFactory.port", porta);
//			propiedades.put("mail.smtp.socketFactory.class", props.getString("mail.smtp.socketFactory.class"));
//			propiedades.put("mail.smtp.socketFactory.fallback", props.getString("mail.smtp.socketFactory.fallback"));
			props.put("mail.smtp.mail.sender", remetente);
//			propiedades.setProperty("mail.smtp.quitwait", props.getString("mail.smtp.quitwait"));
			props.put("mail.smtp.starttls.enable",tls);
			
			// Preparamos la Sesion autenticando al usuario

			Session session = Session.getInstance(props,new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(Email.USER_GMAIL, Email.PASSWORD_GMAIL);
						}
					});

			// Preparamos el Mensaje

			MimeMessage message = new MimeMessage(session);
			message.setSender(new InternetAddress(Email.EMAIL_GMAIL));
			message.setSubject(assunto);
			message.setContent(mensagem, "text/html; charset=utf-8");
			message.setFrom(new InternetAddress(Email.EMAIL_GMAIL));
			message.setReplyTo(InternetAddress.parse(Email.EMAIL_GMAIL));
			StringBuilder destinosConcatenados = new StringBuilder();
			for(int i = 0; i<destinos.size();i++){
				destinosConcatenados.append(destinos.get(i)+",");
			}
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destinosConcatenados.toString()));
			try {
				email = conexao.connect(Email.PROTOCOLO_IMAP_RECEBIMENTO, session, Email.CAIXA_DE_ENTRADA, props,Email.HOST_GMAIL_IMAP,Email.PORT_GMAIL_ENVIO,Email.USER_GMAIL,Email.PASSWORD_GMAIL);
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
			if(email.isConexaoSucedida()){
				Transport.send(message);
				message.setFlag(Flags.Flag.DELETED, true);
				if(email.getFolder().isOpen()){
					email.getFolder().expunge();
					email.getFolder().close(true);
					email.getStore().close();
				}
				email.setMensagemEnviada(true);
			}
		} catch (Throwable e) {
			email.setMensagemEnviada(false);
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			return email;
		}
	}

}
